package com.lxq.live.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lxq.live.pojo.Barrage;
import com.lxq.live.service.VideoService;
import com.lxq.live.util.VideoBarrageRepository;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@Api(tags = "弹幕接口")
public class BarrageController {

    @Autowired
    VideoService videoService;
    @Autowired
    VideoBarrageRepository repository;

    @RequestMapping(value = "/comment/barrage_comment", method = RequestMethod.POST)//需要优化
    public String barrageComment(@RequestParam String uuid, @RequestParam int seconds, @RequestParam String comment,
                                 HttpSession clientSession) {
        var userId = clientSession.getAttribute(clientSession.getId()) + "";
        var videoRow = videoService.getVideoRow(uuid);
        var gSon = new Gson();
        List<List<Barrage>> barrageList = gSon.fromJson(videoRow.getBarrage(), new TypeToken<List<List<Barrage>>>() {
        }.getType());
        var barrage = new Barrage();
        barrage.setUserId(userId);
        barrage.setComment(comment);
        barrageList.get(seconds).add(barrage);
        videoRow.setBarrage(gSon.toJson(barrageList));
        videoService.updateVideoRow(videoRow);
        repository.updateBarrage(uuid);
        return "成功，用户“" + userId + "”为uuid " + uuid + "的第" + seconds
                + "秒" + "提交了一条评论：" + comment;
    }
}
